const App = getApp()
const db = wx.cloud.database()
const _ = db.command
let that
// 监听器
let watcher
Page({

  /**
   * 页面的初始数据
   */
  data: {
    // 用来判断页面是否是首次渲染
    Render: 0,
    // 头部高度
    StatusBar: App.globalData.StatusBar,
    CustomBar: App.globalData.CustomBar,
    // 消息详情弹窗
    msgShow: false,
    // 滚动条
    scrollId: "",
    // tabbar 
    list: [{
        pagePath: '/pages/students/home/index',
        iconPath: "../../images/icon/home-action.png",
        color: "text-blue",
        text: '首页',
      },
      {
        pagePath: '/pages/students/practice/index/index',
        iconPath: "../../images/icon/practice.png",
        color: "text-gray",
        text: '实践',
      },
      {
        pagePath: '/pages/students/teaching/index',
        iconPath: "../../images/icon/teaching.png",
        color: "text-gray",
        text: '教学',
      },
      {
        pagePath: '/pages/students/my/index',
        iconPath: "../../images/icon/my.png",
        color: "text-gray",
        text: '我的',

      }
    ],
    // 轮播
    cardCur: 0,
    swiperList: [{
      id: 0,
      type: 'image',
      name: '看书20分钟',
      text: '静下心看《读者》',
      url: 'https://6361-carlson-yun-6gsfgex5f4754200-1258487737.tcb.qcloud.la/home/deer.jpg?sign=8a88d3a2f4ffd4a0137fe71d4c70cfbf&t=1649427643',
    }, {
      id: 1,
      type: 'image',
      name: '浏览时政新闻',
      text: '对这个世界保持好奇心',
      url: 'https://6361-carlson-yun-6gsfgex5f4754200-1258487737.tcb.qcloud.la/home/deer.jpg?sign=8a88d3a2f4ffd4a0137fe71d4c70cfbf&t=1649427643',
    }, {
      id: 2,
      type: 'image',
      name: '坚持早起',
      text: '早上9点前起床',
      url: 'https://6361-carlson-yun-6gsfgex5f4754200-1258487737.tcb.qcloud.la/home/deer.jpg?sign=8a88d3a2f4ffd4a0137fe71d4c70cfbf&t=1649427643',
    }, {
      id: 3,
      type: 'image',
      name: '努力学习',
      text: '保持永远的上进心',
      url: 'https://6361-carlson-yun-6gsfgex5f4754200-1258487737.tcb.qcloud.la/home/deer.jpg?sign=8a88d3a2f4ffd4a0137fe71d4c70cfbf&t=1649427643',
    }, {
      id: 4,
      type: 'image',
      name: '散散步',
      text: '每天散步30分钟',
      url: 'https://6361-carlson-yun-6gsfgex5f4754200-1258487737.tcb.qcloud.la/home/deer.jpg?sign=8a88d3a2f4ffd4a0137fe71d4c70cfbf&t=1649427643',
    }],
    // 颜色数组
    planList: [{
      color: 'red',
    }, {
      color: 'cyan',
    }, {
      color: 'blue',
    }, {
      color: 'green',
    }, {
      color: 'orange',
    }, {
      color: 'purplered',
    }, {
      color: 'purple',
    }, {
      color: 'brown',
    }, {
      color: 'yellowgreen',
    }, {
      color: 'grey',
    }],

    // 全部的实践任务
    practicelist: [],
    // 正在进行中的实践任务
    Ongoing: [],
    // 全部的课程
    courselist: [],
    // 今天的课程
    dayCourse: [],

    // 消息中心
    message: [],
    // 点击的消息的详情
    msgDetails: "",
  },


  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    that = this
    let UserInfo = App.cache.getUserInfo()
    console.log('获取用户信息:', UserInfo);
    delete UserInfo._id
    // 获取不同时间的问候语
    let greetings = that.getTimeState()
    console.log('greetings', greetings);
    that.setData({
      UserInfo,
      greetings
    })
    // 获取实践任务
    that.getpractice()
    // 获取今日课程和全部课程
    that.getMycourse()
    // 获取消息中心动态
    App.toast.showLoading('获取聊天记录中')
    watcher = db.collection('message')
      .limit(20)
      .where({
        MsgMembers: _.elemMatch({
          account: _.eq(that.data.UserInfo.account)
        })
      }).watch({
        onChange: this.onChange.bind(this),
        onError: function (err) {
          console.error(err)
        }
      })
    App.toast.hideLoading()
  },
  // 消息中心动态监听器
  onChange(snapshot) {
    App.toast.hideLoading()
    console.log('is init data', snapshot.type === 'init')
    console.log(snapshot);
    if (snapshot.type === 'init') {
      console.log('初始化的消息中心数据', snapshot.docs);
      // 获取颜色数组
      let planList = this.data.planList
      let message = snapshot.docs
      message.forEach((item, index) => {
        item.read = App.cache.getCache(item._id)
        switch (item.msgType) {
          case 'CourseMsg':
            item.msgTypeName = '上课提醒'
            break;
          case 'PracticeMsg':
            item.msgTypeName = '实践提醒'
            break;
          default:
            item.msgTypeName = '系统提醒'
            break;
        }
        item.color = planList[index % planList.length].color
      })
      // 排序
      message.sort((x, y) => y.timeTs - x.timeTs)
      console.log('处理过后的消息数组', message);
      this.setData({
        message: message
      })

    } else {
      console.log('更新后的消息中心', snapshot.docs);
      let message = snapshot.docs
      // 获取颜色数组
      let planList = this.data.planList
      message.forEach((item, index) => {
        switch (item.msgType) {
          case 'CourseMsg':
            item.msgTypeName = '上课提醒'
            break;
          case 'PracticeMsg':
            item.msgTypeName = '实践提醒'
            break;
          default:
            item.msgTypeName = '系统提醒'
            break;
        }
        item.color = planList[index % planList.length].color
      })
      console.log('处理过后的消息数组', message);
      // 排序
      message.sort((x, y) => y.timeTs - x.timeTs)
      this.setData({
        message: message
      })

    }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    console.log('这是教师首页');
    console.log('Render变成了', that.data.Render);
    if (that.data.Render === 1) {
      console.log('执行了onShow里的方法');
      // 获取实践任务
      that.getpractice()
      // 获取今日课程和全部课程
      that.getMycourse()
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    that.setData({
      Render: 1
    })
    console.log('Render变成了', that.data.Render);
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    watcher.close()
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  // cardSwiper
  cardSwiper(e) {
    this.setData({
      cardCur: e.detail.current
    })
  },
  // 打开消息详情弹窗

  // 关闭消息详情弹窗
  hideModal(e) {
    this.setData({
      modalName: null
    })
  },

  // 根据时间显示不同的问候语
  getTimeState() {
    // 获取当前时间
    let timeNow = new Date();
    // 获取当前小时
    let hours = timeNow.getHours();
    // 设置默认文字
    let text = ``;
    // 判断当前时间段
    if (hours >= 6 && hours <= 10) {
      text = '早上好';
    } else if (hours > 10 && hours <= 14) {
      text = '中午好';
    } else if (hours > 14 && hours <= 18) {
      text = '下午好';
    } else if (hours > 18 && hours <= 24) {
      text = '晚上好';
    } else if (hours > 0 && hours <= 6) {
      text = '凌晨好';
    }
    return text;
  },

  // 获取我的课程
  getMycourse() {
    db.collection('course').orderBy('courseTimeTs', 'desc').where(_.or([{
          permissions: _.eq(that.data.UserInfo.permissions)
        },
        {
          lecturer: {
            account: _.eq(that.data.UserInfo.account)
          }
        },
        {
          courseMember: _.elemMatch({
            account: _.eq(that.data.UserInfo.account)
          })
        }
      ]))
      .get({
        success: function (res) {
          console.log(res.data)
          // 获取全部课程
          let course = res.data
          console.log('初始数据', course);

          // 获取当天的时间戳
          let today = new Date(new Date(new Date().toLocaleDateString()).getTime());
          today = Date.parse(today)
          console.log('当天零点的时间戳', today);
          // 获取当天23点59分59秒的时间戳 
          let tomorrow = new Date(new Date(new Date().toLocaleDateString()).getTime() + 24 * 60 * 60 * 1000 - 1);
          tomorrow = Date.parse(tomorrow)
          console.log('当天23.59.59的时间戳', tomorrow);
          console.log('当前的时间戳', App.Time.formatTime(Date.now()));
          let dayCourse = []
          // 给每个课程加上颜色 planList(颜色数组)
          let planList = that.data.planList
          // 筛选今天的课程
          course.forEach((item, index) => {
            dayCourse = item.courseTime.filter(x => {
              return x.addTime < tomorrow && x.endTime - Date.now() > 0
            })
            item.color = planList[index % planList.length].color
          });

          // 将过滤出来的课程做一个状态，还有多久上课，是否正在上课
          dayCourse.forEach((item, index) => {
            item.addTime = item.addTime - Date.now()
            item.endTime = item.endTime - Date.now()
            item.color = planList[index % planList.length].color
            item.today = '今'
          })
          console.log('筛选今日的课程', dayCourse);
          console.log('获取全部课程', course);
          that.setData({
            courselist: course,
            dayCourse: dayCourse
          })
        }
      })
  },
  // 获取实践任务
  getpractice() {
    db.collection('practice').orderBy('timeTs', 'desc').where(_.or([{
          'creator.account': _.eq(that.data.UserInfo.account)
        },
        {
          'permissions': _.eq(that.data.UserInfo.permissions)
        },
        {
          courseMember: _.elemMatch({
            account: _.eq(that.data.UserInfo.account)
          })
        }

      ]))
      .get({
        success: function (res) {
          let list = res.data
          // 获取自定义的照片
          let swiperList = that.data.swiperList
          let Ongoing = []
          list.forEach((item, index) => {
            item.image = swiperList[index].url
            Ongoing = list.filter(item => {
              return item.practiceSwitch === true
            })
          })
          console.log('全部的实践任务', list);
          console.log('正在进行中的任务', Ongoing);
          that.setData({
            practicelist: list.slice(0, 5),
            Ongoing: Ongoing.slice(0, 5),
          })
        }
      })
  },
  // 查看点击的消息的详情
  msgDetails(e) {
    let idx = e.currentTarget.dataset.idx
    let target = e.currentTarget.dataset.target
    let id = e.currentTarget.dataset.id
    let message = that.data.message
    let msgDetails = message.filter(item => {
      return item._id === id
    })
    console.log('msgDetails', msgDetails[0]);
    //  将消息改成已读
    App.cache.setCache(msgDetails[0]._id, true)
    that.setData({
      modalName: target,
      msgDetails: msgDetails[0],
      ['message[' + idx + '].read']: true
    });
  },



  // 跳转到实践列表
  practiceRoute(e) {
    const {
      detail,
      currentTarget
    } = e
    let identityId = currentTarget.id.toLowerCase()
    console.log(identityId);
    App.route.navTo('/pages/' + identityId + '/practice/list/index')
  },
  // 跳转到实践详情
  practiceDetailsRoute(e) {
    console.log(e);
    const {
      detail,
      currentTarget
    } = e
    let identityId = currentTarget.id.toLowerCase()
    let practiceId = currentTarget.dataset.practiceid
    console.log('传值前', identityId, practiceId);
    App.route.navTo('/pages/' + identityId + '/practice/details/index', practiceId)
  },

  // 课程路由
  couarseRoute(e) {
    let data = e.currentTarget.dataset
    console.log(data);
    App.route.navTo('/pages/course/list/index', data)
  },

  // 消息路由
  msgRoute() {
    App.route.navTo('/pages/message/list/index')
  }
})